#include <hidef.h>
#include "derivative.h"
#include "pwm.h"

void pwm_init(void) {
  PWMSDN = 0x00;    // PWM Shutdown - Disable Shutdown Functionality
  PWMPRCLK = 0x77;  // Clock A & B Prescaler - Scale by 32
  PWMSCLA = 0x08;   // Clock SA Scaler - Scale Clock A by 2
  PWMSCLB = 0x08;   // Clock SB Scaler - Scale Clock B by 2
  PWMCAE = 0x00;    // Left Align PWMs
  PWMCLK = 0xFF;     // PWM Clock Select - Use Clocks A & B
  PWMPOL |= 0xFF;    // PWM Polarity Select - Start High
  PWMCTL = 0x00;     // PWM Control Register - Use 8-bit PWMs 
  PWME = 0x00;      // Disable all PWM Ports
  
  PWMPER0 = 200;      // PWM Period - Set to 200 for ease of calculating duty cycle
  PWMPER1 = 234;
  PWMPER2 = 200;
  PWMPER3 = 200;
  PWMPER4 = 200;
  PWMPER5 = 200;
  PWMPER6 = 200;
  PWMPER7 = 200;
}

void pwm_set(int duty, int channel) {
 switch(channel) {
  case 0:
    PWMDTY0 = duty;
    PWME_PWME0 = 1;
    break;
  case 1:
    PWMDTY1 = duty;
    PWME_PWME1 = 1;
    break;
  case 2:
    PWMDTY2 = duty;
    PWME_PWME2 = 1;
    break;
  case 3:
    PWMDTY3 = duty;
    PWME_PWME3 = 1;
    break;
  case 4:
    PWMDTY4 = duty;
    PWME_PWME4 = 1;
    break;
  case 5:
    PWMDTY5 = duty;
    PWME_PWME5 = 1;
    break;  
  case 6:
    PWMDTY6 = duty;
    PWME_PWME6 = 1;
    break;
  case 7:
    PWMDTY7 = duty;
    PWME_PWME7 = 1;
    break;
  default:
    PWMDTY0 = duty;
    PWME_PWME0 = 1;                       
  }

}